/*
 * Importer.java
 * 
 * This class imports data from a external file into database.
 * 
 * Copyright 2013 Santi Ruiz Andrés <starfly1570@gmail.com>
 * 
 * This file is part of Drawer of Marks.
 * 
 * Drawer of Marks is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Drawer of Marks is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Drawer of Marks.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package blogspot.santiruizpro.drawerofmarks.model;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import android.content.ContentValues;

/**
 * @author starfly1570
 */
public class Importer {

	/**
	 * Imports data from a marks package to database.
	 * 
	 * @param database the target database
	 * @param marksPackage the file
	 */
	public void importMarksPackage(DBAccess database,File marksPackage) {
		try {
			BufferedReader br = new BufferedReader(new FileReader(marksPackage));
			for ( int i = 0; i < 3; i++ ) {
				String tableToImport = i == 0 ? "subjects" : i == 1 ? "divisions" : "exams";
				String line = br.readLine();
				while ( line != null && !line.contains("END-TABLE") ) {
					ArrayList<String> columnNames = database.getTableColumnNames(tableToImport);
					String[] columns = line.split(":");
					ContentValues cv = new ContentValues();
					for ( int j = 0; j < columns.length; j++ ) {
						cv.put(columnNames.get(j), columns[j]);
					}
					if ( database.query("Select * from " + tableToImport + " where pkey=" + columns[0]).size() == 0 )
						database.insert(tableToImport, cv);
					line = br.readLine();
				}
			}
			br.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
